package handler

import (
	"github.com/gin-gonic/gin"
	"house/api/requset"
	"house/api/resp"
	"house/internal/dao"
	"house/internal/model"
)

// 添加订单
func AddOrder(c *gin.Context) {
	var req requset.AddOrderReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	//权限
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.UType != 1 {
		resp.Error(c, 10000, "不是买家权限", nil)
		return
	}
	//判断房源
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 10000, "房源不存在", nil)
		return
	}
	//添加订单
	result := dao.Create(&model.Order{
		UserId:  c.GetUint("userId"),
		HouseId: req.HouseId,
		Price:   house.Price,
		Status:  1,
	})
	if !result {
		resp.Error(c, 10000, "订单添加失败", nil)
		return
	}
	//锁定房源
	dao.Update(&model.House{
		Id:     req.HouseId,
		Status: 4, //4为锁定中
	})
	resp.Success(c, true) //返回

}

// 上传首付凭证
func UploadPayUrl(c *gin.Context) {
	var req requset.UploadPayUrlReq
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 10000, "验证失败", err.Error())
		return
	}

	//业务逻辑
	//权限
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.UType != 1 {
		resp.Error(c, 10000, "不是买家权限", nil)
		return
	}
	var order model.Order
	dao.GetOneById(req.Id, &order)
	if order.Status != 1 {
		resp.Error(c, 10000, "不是待上传首付凭证状态", nil)
		return
	}
	result := dao.Update(&model.Order{
		Id:     req.Id,
		PayUrl: req.PayUrl,
		Status: 2, //2为待审核
	})
	if !result {
		resp.Error(c, 10000, "上传首付凭失败", nil)
		return
	}
	//返回
	resp.Success(c, true)

}
